package com.ahdms.es.engine;

import com.ahdms.es.bean.enums.VerifyCertCode;
import com.ahdms.es.config.PropertiesConfig;
import com.ahdms.es.exceptions.VerifyCertException;
import com.ahdms.es.util.GeneralSignatureUtils;
import com.ahdms.es.util.LdapUtils;
import org.bouncycastle.asn1.x509.Certificate;

import java.io.IOException;
import java.util.Date;
import java.util.Optional;

/**
 * PKI证书验证
 *
 * @author qinxiang
 * @date 2021-04-09 10:20
 */
public class PKICertVerifyEngine extends X509CertVerifyEngine {

    @Override
    public boolean verifyCertTrustChain(Certificate cert) throws VerifyCertException {
        try {
            if(!PropertiesConfig.isPkmCertVerify()){
                return true;
            }
            Certificate pkiRootCert = Optional.ofNullable(PropertiesConfig.getPkiRootCert())
                    .orElseThrow(() -> new VerifyCertException(VerifyCertCode.Verify_ROOTCERT_EMPTY));
            byte[] srcBytes = cert.getTBSCertificate().getEncoded("DER");
            byte[] signValue = cert.getSignature().getBytes();
            String signAlg = cert.getSignatureAlgorithm().getAlgorithm().getId();
            boolean verifySign = GeneralSignatureUtils.verifySign(pkiRootCert, signAlg, srcBytes, signValue);
            if(!verifySign){
                throw new VerifyCertException(VerifyCertCode.Trust_Chain_Fail);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e){
            throw new VerifyCertException(VerifyCertCode.CERT_SIGN_Algorithm_Invalid);
        }
        throw new VerifyCertException(VerifyCertCode.CERT_FORMART_FAIL);
    }

    @Override
    public boolean verifyCertIsRevoke(Certificate cert)  {
        if(!PropertiesConfig.isCrlEnable()){
            return true;
        }
        Date date = LdapUtils.queryLdapByPki(cert);
        return date == null;
    }

    @Override
    public boolean verifyCertByOcsp(Certificate cert) {
        return true;
    }
}
